Grouping¶
group_by_first_letter.py
¶
🖌 Grouping Pattern¶
- Define the key
- For a given item, what group does it belong in?
- Often you will use a separate function for this
- Initialize the key (if necessary)
- If the key hasn't been seen before, setup a new group for it
- i.e.
if key not in groups
, then initialize the key, often to an empty list
- Add the item to the group
- e.g. append the item to the list for the respective group
👩🏾🎨 Group by size¶
Group a sequence of words by their length.
Use an input loop. Print word groups at the end.
group_by_size.py
¶
🎨 tuple
+ dict
¶
In [1]:
data = {
('Monday', '1pm'): 'CS 110',
('Tuesday', '2pm'): 'CS 235',
('Wednesday', '1pm'): 'CS 110',
('Thursday', '2pm'): 'CS 235',
('Friday', '1pm'): 'CS 110'
}
In [2]:
data['Monday']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[2], line 1 ----> 1 data['Monday'] KeyError: 'Monday'
In [3]:
data['Monday', '1pm']
Out[3]:
'CS 110'
You can use a tuple
as a key in a dictionary.
In [4]:
time = ['Monday', '1pm']
data[time]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[4], line 2 1 time = ['Monday', '1pm'] ----> 2 data[time] TypeError: unhashable type: 'list'
You can't use a list
or a dict
as a key in a dictionary.
If you see an "unhashable type" TypeError
, it's because you are trying to use something as a key that doesn't work as a key (list
and dict
are the more common offenders).
You'll learn what "unhashable" means in CS 235. 🙂
👨🏻🎨 First and Last¶
Group words based on their first and last letters.
Use an input loop. Print the groups at the end.
first_and_last.py
¶
👩🏻🎨 Vowelly¶
🖌 Grouping Pattern¶
- Define the key
- For a given item, what group does it belong in?
- Often you will use a separate function for this
- Initialize the key (if necessary)
- If the key hasn't been seen before, setup a new group for it
- i.e.
if key not in groups
, then initialize the key, often to an empty list
- Add the item to the group
- e.g. append the item to the list for the respective group